package com.kexin.common.utils;


import org.springframework.util.DigestUtils;

import com.kexin.common.exception.WebException;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonUtils {

    public static String passwordMd5(String password){
        return DigestUtils.md5DigestAsHex((password).getBytes());
    }
//    public static void writeJson(HttpServletResponse response, Result error) {
//        try {
//            response.setContentType("text/json;charset=UTF-8");
//            response.getWriter().write(JSON.toJSONString(error));
//        } catch (IOException e) {
//            Logger log = LoggerFactory.getLogger(CommonUtils.class);
//            log.error("---writeJson:"+e.getMessage(),e);
//        }
//    }

    public static<T> Map<String,List<Object>> listObjToMapList(List<T> listOb)  {
        Class<? extends Object> tClass=null;
        Field[] fields=null;

        Map<String,List<Object>> map = new HashMap<>();
        try{
            for (T obj:listOb){
                if (tClass==null){
                     tClass= obj.getClass();
                     fields = tClass.getDeclaredFields();
                }
                for (Field field:fields){
                    String name = field.getName();
                    if ("serialVersionUID".equals(name)){
                        continue;
                    }
                    if (map.get(name)==null){
                        map.put(name,new ArrayList());
                    }
                    String uname = name.substring(0, 1).toUpperCase() + name.substring(1);
                    Method m = tClass.getMethod("get"+uname);
                    map.get(name).add(m.invoke(obj));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new WebException("数据格式转换报错");
        }
        return map;
    }

}
